package cn.lingyangwl.framework.data.mate.fieldbind.aspect;

import cn.lingyangwl.framework.data.mate.annotations.FieldBindHandle;
import cn.lingyangwl.framework.data.mate.fieldbind.FieldBindHandler;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 字段绑定处理
 *
 * @author shenguangyang
 */
@Aspect
@Component
public class FieldBindSetterAspect {
    private static final Logger log = LoggerFactory.getLogger(FieldBindSetterAspect.class);
    @Resource
    private FieldBindHandler fieldBindHandler;

    // 配置织入点
    @Pointcut("@annotation(cn.lingyangwl.framework.data.mate.annotations.FieldBindHandle)")
    public void pointcut() {
    }

    @AfterReturning(pointcut = "pointcut()", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {
        // 获得注解
        FieldBindHandle fieldBindHandle = getAnnotationLog(joinPoint);
        if (Objects.isNull(fieldBindHandle)) {
            return;
        }
        fieldBindHandler.handleField(result);
    }


    /**
     * 是否存在注解，如果存在就获取
     */
    private FieldBindHandle getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(FieldBindHandle.class);
        }
        return null;
    }
}
